// 前台首页所有api接口
'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'api接口';
    // 获取数据库用户表blog_content（表名）的数据

    const result = await this.app.mysql.get('blog_content', {});
    console.log(result);
  }
  // 文章列表
  async getArticleList() {
    // 拼接sql语句 select (属性名) from (表名1)  left join (表名2) ON (条件)
    // type表查询typename
    const sql = 'SELECT article.id as id,' +
      'article.title as title,' +
      'article.introduce as introduce,' +
      // 'article.addTime as addTime,' +
      "FROM_UNIXTIME(article.addTime,'%Y-%m-%d %H:%i:%s' ) as addTime," +
      'article.view_count as view_count ,' +
      'type.typeName as typeName ' +
      'FROM article LEFT JOIN type ON article.type_id = type.Id';
    // 执行sqle语句
    const results = await this.app.mysql.query(sql);
    const { ctx } = this;
    // 这个路由地址http://127.0.0.1:7001/default/getArticleList【router.js进行配置】接口下只是获取这组json数据
    ctx.body = {
      data: results,
    };
  }
  // 文章详情
  async getArticleById() {
    //  let  id = this.ctx.params.id
    // eslint-disable-next-line no-unused-vars
    const { ctx } = this;
    const id = this.ctx.params.id;
    console.log(1111111111,id);

    let sql = 'SELECT article.id as id,' +
    'article.title as title,' +
    'article.introduce as introduce,' +
    'article.article_content as article_content,' +
    "FROM_UNIXTIME(article.addTime,'%Y-%m-%d %H:%i:%s' ) as addTime," +
    'article.view_count as view_count,' +
    'type.typeName as typeName,' +
    'type.Id as typeId ' +
    'FROM article LEFT JOIN type ON article.type_id = type.Id ' +
    'WHERE article.id='+id
    const result = await this.app.mysql.query(sql);
    console.log(result);
    // 一定要写，不然上下文404 Not Found
    ctx.body = { data: result };
  }
  // 得到类别名称和编号
  async getTypeInfo(){
    // type 表面
      const result = await this.app.mysql.select('type')
      this.ctx.body = {data:result}
  }

  //根据类别ID获得文章列表
async getListById(){
  let id = this.ctx.params.id
  let sql = 'SELECT article.id as id,'+
  'article.title as title,'+
  'article.introduce as introduce,'+
  "FROM_UNIXTIME(article.addTime,'%Y-%m-%d %H:%i:%s' ) as addTime,"+
  'article.view_count as view_count ,'+
  'type.typeName as typeName '+
  'FROM article LEFT JOIN type ON article.type_id = type.Id '+
  'WHERE type_id='+id
  const result = await this.app.mysql.query(sql)
  this.ctx.body={data:result}

}

}


module.exports = HomeController;

